package com.stu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stu.commons.ServerResponce;
import com.stu.commons.ServerResponse;
import com.stu.mapper.UsersMapper;
import com.stu.pojo.CustomerTokenDTO;
import com.stu.pojo.Users;
import com.stu.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stu.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UsersServiceImpl implements IUsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public ServerResponce login(Users users) {
        QueryWrapper<Users> wrapper =  new QueryWrapper<>();
        wrapper.eq("user_telno",users.getUserTelno());
        wrapper.eq("user_pwd",users.getUserPwd());

        Users loginUser = usersMapper.selectOne(wrapper);

        if(loginUser !=null) {
            Integer userId = loginUser.getUserId();
            int userStatus = loginUser.getUserStatus();
            String token = JwtUtil.generateToken(userId.toString(), userStatus);

            String userNickname = loginUser.getUserNickname();
            String userImage = loginUser.getUserHeading();

            Map<String, Object> responseData = new HashMap<>();
            responseData.put("userNickname", userNickname);
            responseData.put("token", token);
            responseData.put("userImage", userImage);
            responseData.put("userStatus", userStatus);

            return ServerResponce.success("登录成功", responseData);
        }else
            return ServerResponce.fail("登录失败",null);
    }


    @Override
    public Users selectById(Integer userId) {
        Users user = usersMapper.selectById(userId);
        return user;
    }

    @Override
    public ServerResponse getById(Integer userId) {
        Users user = usersMapper.selectById(userId);
        if(user!=null)
            return ServerResponse.success("查询用户成功", user);
        else
            return ServerResponse.fail("查询用户失败", null);
    }

    @Override
    public List<Users> getAll() {
        return usersMapper.selectList(null);
    }

    @Override
    public ServerResponse save(Users users) {
        int rows = usersMapper.insert(users);
        if(rows > 0)
            return ServerResponse.success("查询成功！",users);
        else
            return ServerResponse.fail("查询失败！请重试！",null);
    }

    @Override
    public Users getUpdateUsersById(Integer userId) {
        return usersMapper.selectById(userId);
    }

    @Override
    public ServerResponse updateUser(Users users) {
        int rows = usersMapper.updateById(users);
        if (rows !=0)
            return ServerResponse.success("修改用户成功", users);
        return ServerResponse.fail("修改用户失败", null);
    }

}
